package fr.ordre66.vlcs.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import fr.ordre66.vlcs.dto.User;
import fr.ordre66.vlcs.services.IUserManager;

@Service("userDetailsservice")
public class VlcsUserDetailsService implements UserDetailsService{

	@Autowired IUserManager userManager;
	
	@Override
	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException, DataAccessException {

		User user = userManager.get(login);
		return buildUserFromUserEntity(user);
	}
	
	org.springframework.security.core.userdetails.User buildUserFromUserEntity(User user) {

		String username = user.getLogin();
		String password = user.getPassword();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new GrantedAuthorityImpl("ROLE_USER"));

		org.springframework.security.core.userdetails.User userSpringS = new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authorities);
		return userSpringS;
	}
}
